package au.edu.unsw.editingtool.db;

import java.sql.SQLException;
import java.util.Hashtable;

import au.edu.unsw.editingtool.global.EditingToolException;
import au.edu.unsw.editingtool.global.EditingToolGlobalConstant;

public class DBClaims extends DBManager {
	
	protected void setupDBMapping() {
		if (MappingTable.size() > 0)
			return;
		MappingTable.put("Author", "author");
		MappingTable.put("Affiliation", "affiliation");
		MappingTable.put("Publication", "pid");
		MappingTable.put("Status", "status");
		MappingTable.put("Date", "date");
		MappingTable.put("Note", "note");
	}
	
	public DBClaims() {
		this.table = "claims";
		this.primaryKeys = new String[]{"Author", "Publication"};
		this.setupDBMapping();
	}
	
	// need to return different status to indicate weather there's no claim or it's not available.
	public int CheckClaims(String author, String pid) throws EditingToolException, ClassNotFoundException, SQLException {
		String fields[] = {"Status"};
		
		this.setTable(this.table, "");
		this.setFieldsCondition("Author", this.setEqual(author));
		this.setFieldsCondition("Publication", this.setEqual(pid));
		this.addField(fields);
		
		this.initDB();
		this.selectRecords();
		if (this.ResultSet == null) {
			this.clean();
			return 2;
		}
		if (!this.collectResults())
			return 2;
		for (int row = 0; row < Result.length / fields.length; row++) {
			for (int column = 0; column < fields.length; column++) {
				if (Result[row][column].equals(EditingToolGlobalConstant.claimStatusClaimed)) {
					this.clean();
					return 0;
				}
			}
		}
		this.clean();
		return 1;
	}
	
	public void changeClaimStatus(String status, Hashtable<String, String> keys) throws ClassNotFoundException, SQLException {
		this.setTable(this.table, "");
		for (int i=0; i<this.primaryKeys.length; i++) {
			this.setFieldsCondition(this.primaryKeys[i], setEqual(keys.get(this.primaryKeys[i])));
		}
		
		Hashtable<String, String> record = new Hashtable<String, String>();
		record.put("Status", status);
		
		this.initDB();
		this.setColumnValues(record);
		this.updateRecords();
		this.clean();
	}
	
	// affiliation and pid is already solved
	//   -> affiliation can be found in login table. 
	public void addClaim(Hashtable<String, String> claim) throws EditingToolException, ClassNotFoundException, SQLException {
		this.setTable(this.table, "");
		claim.put("Status", EditingToolGlobalConstant.claimStatusRequested);
		claim.put("Date", "CURRENT_TIMESTAMP()");
		claim.put("Note", "add a new claim.");
		this.setColumnValues(claim);
		
		this.initDB();
		this.insert(false, false);
		this.clean();
	}
	
}
